#include <Windows.h>
#include "../rendersystem/px_rendersystem.h"
#include "../utility/px_macros.h"
#include "../utility/px_gl.h"
#include <math.h>
#include "../gamestate/px_gamemain.h"
#include "../utility/px_system.h"
#include "GL/glew.h"
PXBOOL applicationDidFinishLaunching()
{
	return PXTURE;
}
LARGE_INTEGER s_animationInterval;
void setAnimationInterval(double interval)
{
	LARGE_INTEGER nFreq;
	QueryPerformanceFrequency(&nFreq);
	s_animationInterval.QuadPart = (LONGLONG)(interval * nFreq.QuadPart);
}


static int run()
{
	MSG msg;
	LARGE_INTEGER nFreq;
	LARGE_INTEGER nLast;
	LARGE_INTEGER nNow;

	QueryPerformanceFrequency(&nFreq);
	QueryPerformanceCounter(&nLast);

	// Initialize instance and cocos2d.
	if (!applicationDidFinishLaunching())
	{
		return 0;
	}

	PXVIEW* pMainWnd =share_PXVIEW();
	center_window(pMainWnd);
	set_projection(pMainWnd);

	ShowWindow(pMainWnd->hwind, SW_SHOW);
	set_gamestate(PX_GAMESTATE_RUN);
	setAnimationInterval((double)1/30);
	while (1)
	{
		if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			// Get current time tick.
			QueryPerformanceCounter(&nNow);

			// If it's the time to draw next frame, draw it, else sleep a while.
			if (nNow.QuadPart - nLast.QuadPart >s_animationInterval.QuadPart )
			{
				nLast.QuadPart = nNow.QuadPart;
		        
				game_mainloop();	
			    swap_buffer(pMainWnd);
			}
			else
			{
				Sleep(0);
			}
			continue;
		}

		if (WM_QUIT == msg.message)
		{
			// Quit message loop.
			break;
		}

		// Deal with windows message.
		if (/*! m_hAccelTable || */! TranslateAccelerator(msg.hwnd,NULL /*m_hAccelTable*/, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPTSTR    lpCmdLine,
	int       nCmdShow) 
{
		UNREFERENCED_PARAMETER(hPrevInstance);
		UNREFERENCED_PARAMETER(lpCmdLine);
		// create the application instance
		PXVIEW* eglView =share_PXVIEW();
		eglView->hwind = NULL;
		create_window(eglView,TEXT("Panda-x"),SCREEN_WIDTH, SCREEN_HEIGHT);
	    return	run();
}
